//
//  CookViewController.m
//  Cook Street
//
//  Created by dllo on 15/8/8.
//  Copyright (c) 2015年 杨元石. All rights reserved.
//

#import "CookMenuController.h"
#import "CookModel.h"
#define WIDTH ([UIScreen mainScreen].applicationFrame.size.width)
#define HEIGHT ([UIScreen mainScreen].applicationFrame.size.height)
#import "Cook_SecViewController.h"
#import "CookCollectionViewCell.h"
#import "AFN.h"
#import "Cook_Thir_ViewController.h"
#import "NetworkHandle.h"


@interface CookMenuController ()<UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,UISearchBarDelegate>

@property (nonatomic, strong) UITableView *tableView;

//第一次解析存入的数组  tableView
@property (nonatomic, strong) NSMutableArray *array;

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *flowLayout;

@property (nonatomic, strong) NSString *name;

//存入的数组   collectionView
@property (nonatomic, strong) NSMutableArray *DataArray;
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIImageView * bgImg;  //背景图
@property (nonatomic, strong) NSMutableArray *searchArr;
@property (nonatomic, strong) UITableView *searchTableView;
@property (nonatomic, strong) UITableViewCell *cell;

@property (nonatomic, strong) NSString *str;   //关键字高亮

@property (nonatomic, strong)UIView *animation;

//tableView -> collectionView 自定义方法
-(void)CollectionView:(CookModel *)cookModel;

@end

@implementation CookMenuController

#pragma mark - 懒加载数组
- (NSMutableArray *)array
{
    if (_array == nil) {
        
        NSMutableArray *array = [NSMutableArray arrayWithCapacity:0];
        
        _array = array;
    }
    return _array;
}
- (NSMutableArray *)DataArray
{
    if (_DataArray == nil) {
        
        NSMutableArray *dataArray = [NSMutableArray arrayWithCapacity:0];
        _DataArray = dataArray;
    }
    return _DataArray;
}

- (NSMutableArray *)searchArr
{
    if (_searchArr == nil) {
        NSMutableArray *searchArr = [NSMutableArray arrayWithCapacity:0];
        _searchArr = searchArr;
    }
    return _searchArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
   
    self.navigationItem.title = @"分类";
    
    self.bgImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    self.bgImg.image = [UIImage imageNamed:@"fenlei"];
    [self.view addSubview:self.bgImg];
    [self animationView];
    [self GET];
    [self creatTableView];
    [self creatCollectionView];
    [self creatsearchTableView];
    

    self.searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 64, WIDTH, WIDTH / 4)];
    [self.searchBar setBarStyle:UIBarStyleDefault];
    self.searchBar.placeholder = @"搜菜谱 如: 孜然羊肉 或 披萨";
    [self.searchBar setTintColor:[UIColor colorWithRed:90./255. green:169./255. blue:17./255. alpha:1]];
    [self.searchBar setBarTintColor:[UIColor lightGrayColor]];
    self.searchBar.delegate = self;
    [self.view addSubview:self.searchBar];
    
    // Do any additional setup after loading the view.
}



#pragma mark - 加载动画
- (void)animationView
{
    self.animation = [[UIView alloc]initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT  -64)];
    self.animation.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.animation];
    
    NSMutableArray *arr = [[NSMutableArray alloc]init];
    UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(WIDTH / 2 - 65, HEIGHT / 2 -100, WIDTH / 375 * 130, HEIGHT / 667 *130)];
    
    [imageView setBackgroundColor:[UIColor redColor]];
    for (NSInteger i = 1; i < 5; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"%ld" , i]];
        [arr addObject:image];
    }
    [self.animation addSubview:imageView];
    imageView.animationImages = arr;
    imageView.animationRepeatCount = 0;
    imageView.animationDuration = 0.5;
    [imageView startAnimating];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(WIDTH/2-50, HEIGHT /2-130, WIDTH / 375 * 100, HEIGHT / 667 * 30)];
    label.text = @"玩命加载中...";
    [self.animation addSubview:label];
    
}




#pragma mark- 创建CollectionView
-(void)creatCollectionView
{
    self.flowLayout = [[UICollectionViewFlowLayout alloc]init];
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake((WIDTH - 30 ) /2.5,  64 + HEIGHT / 5, WIDTH - (WIDTH - 30 ) /3, HEIGHT -  WIDTH / 4 - 128) collectionViewLayout:self.flowLayout];
    self.flowLayout.itemSize = CGSizeMake((WIDTH - 30 ) /3.5, 40);
    self.flowLayout.sectionInset = UIEdgeInsetsMake(20, 0, 10, 40);
    
    [self.collectionView setBackgroundColor:[UIColor whiteColor]];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.bounces = NO;
    self.collectionView.backgroundColor = [UIColor clearColor];
    [self.collectionView registerClass:[CookCollectionViewCell class] forCellWithReuseIdentifier:@"reuseld"];
    
    [self.view addSubview:self.collectionView];

}



#pragma mark- GET
-(void)GET
{
    [NetworkHandle getDataWithURL:@"http://apis.juhe.cn/cook/category?%20key=1a598cdd68c9b10550d6403b5db054e6&dtype=json&parentid=" completion:^(id result) {
        
        NSMutableArray *resultArr = [result objectForKey:@"result"];
        
        for (NSMutableDictionary *dic in resultArr) {
            
            CookModel *cook = [[CookModel alloc]init];
            [cook setValuesForKeysWithDictionary:dic];
            [self.array addObject:cook];
        }
        [self changeValue];
        [self.tableView reloadData];
        [self.animation removeFromSuperview];
    }];
}

#pragma mark- 点击菜谱直接出来collectionView
-(void)changeValue
{
    CookModel *cook = [self.array objectAtIndex:0];
    [self CollectionView:cook];
}




#pragma mark- UITableView
-(void)creatTableView
{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64 + HEIGHT / 5, (WIDTH - 30 ) /2.5 , HEIGHT -  WIDTH / 4 - 140) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //    右侧滑块隐藏
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.bounces = NO;
    self.tableView.separatorColor = [UIColor clearColor];
    self.tableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.tableView];

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        return self.array.count;
    }if (tableView == self.searchTableView) {
        return self.searchArr.count;
    }
    return 0;
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        return 60;
    }
    if (tableView == self.searchTableView) {
        return 50;
    }
 
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{    
    if (tableView == self.tableView) {
        static NSString *cellId = @"cell";
        self.cell = [self.tableView dequeueReusableCellWithIdentifier:cellId];
        if (self.cell == NO) {
            
            self.cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        
        CookModel *cook = [self.array objectAtIndex:indexPath.row];
        self.cell.textLabel.text = cook.name;
        self.cell.textLabel.font = [UIFont systemFontOfSize:23];
        self.cell.textLabel.textAlignment = 1;
        
        //点击cell变颜色  背景颜色
        self.cell.selectedBackgroundView = [[UIView alloc] initWithFrame:self.cell.frame];
        self.cell.selectedBackgroundView.backgroundColor = [UIColor clearColor];
        //字体颜色
        self.cell.textLabel.highlightedTextColor = [UIColor colorWithRed:90./255. green:169./255. blue:17./255. alpha:1];
        self.cell.backgroundColor = [UIColor clearColor];
        self.cell.textLabel.font = [UIFont systemFontOfSize:17];
        return self.cell;
    }
    
    static NSString *cellID1 = @"cell1";
    UITableViewCell *cell = [self.searchTableView dequeueReusableCellWithIdentifier:cellID1];
    if (cell == NO) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID1];
    }
    
    CookModel *cook = [self.searchArr objectAtIndex:indexPath.row];
    //    关键字高亮
    NSString *str = cook.title;
    //    初始化一个富文本属性
    NSMutableAttributedString *arrtiString = [[NSMutableAttributedString alloc]initWithString:str];
    //    搜索指定文字的范围
    NSRange range = [str rangeOfString:self.str];
    //    给富文本添加属性
    [arrtiString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    cell.textLabel.attributedText = arrtiString;
    return cell;
}


#pragma mark- 点击tableView的cell
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.tableView) {
        CookModel *cook = [self.array objectAtIndex:indexPath.row];
        [self CollectionView:cook];
    }
    else if (tableView == self.searchTableView){
        
        Cook_Thir_ViewController *thir = [[Cook_Thir_ViewController alloc]init];
        [self.navigationController pushViewController:thir animated:YES];
        CookModel *c = [self.searchArr objectAtIndex:indexPath.row];

        thir.title = c.title;
        thir.tag = c.tags;
        thir.ing = c.ingredients;
        thir.bur = c.burden;
        thir.stepArr = c.steps;
      //  thir.pic = c.albums;

        
    }
    
}




#pragma mark- UICollectionView
-(void)CollectionView:(CookModel *)cookModel
{
    self.DataArray = cookModel.list;
    
    [self.collectionView reloadData];
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.DataArray.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuseID = @"reuseld";
    CookCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseID forIndexPath:indexPath];
    
    NSDictionary *dic = [self.DataArray objectAtIndex:indexPath.row];
    self.name = [dic objectForKey:@"name"];
    
    cell.label.text = self.name;
    cell.label.layer.borderWidth = YES;
    cell.label.layer.cornerRadius = 20;
    cell.label.layer.borderColor = [[UIColor lightGrayColor]CGColor];
    cell.label.font = [UIFont systemFontOfSize:16];
    
    return cell;
}

#pragma mark- 点击collectionView的cell
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    Cook_SecViewController *sec = [[Cook_SecViewController alloc]init];
    NSDictionary *dic = [_DataArray objectAtIndex:indexPath.row];
    NSString *s = [dic objectForKey:@"name"];
    NSString *str = [dic objectForKey:@"id"];
    sec.name = s;
    sec.num = str;

    [self.navigationController pushViewController:sec animated:YES];
  
}




#pragma mark-UISearachBar

//开始编辑状态
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    
    [self.searchBar setShowsCancelButton:YES animated:YES];
    [self.searchBar becomeFirstResponder];
}

//点击cancel时候
-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.searchBar setShowsCancelButton:NO animated:YES];
    [self.searchBar resignFirstResponder];
    self.searchTableView.hidden = YES;
    self.tableView.hidden = NO;
    self.collectionView.hidden = NO;
    [self.searchArr removeAllObjects];
  
}


-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
    self.tableView.hidden = YES;
    self.collectionView.hidden = YES;
    self.searchTableView.hidden = NO;    
    
    if (self.searchBar.text.length == 0) {
        self.searchTableView.hidden = YES; //控制下拉列表的隐现
    }else{
        self.searchTableView.hidden = NO;
        [self.searchArr removeAllObjects];
    }
    
    self.str = searchText;
    NSString * url = [self.str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    
    [AFN urlString:[NSString stringWithFormat:@"http://caipu.yjghost.com/index.php/query/read?menu=%@",url]  getAFNdata:^(id responseObject) {
        
        if ([[responseObject objectForKey:@"reason"] isEqualToString:@"result is empty"]) {
            
            [self.searchArr removeAllObjects];
            UIAlertView * al = [[UIAlertView alloc]initWithTitle:@"对不起" message:@"搜不到您所需要的"delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [al show];
        }
        
        NSMutableDictionary *resultDic = [responseObject objectForKey:@"result"];
        NSMutableArray *dataArray = [resultDic objectForKey:@"data"];
        
        for (NSMutableDictionary *dic in dataArray) {
            
            CookModel *co = [[CookModel alloc]init];
            [co setValuesForKeysWithDictionary:dic];
            [self.searchArr addObject:co];
        }
        [self.searchTableView reloadData];
    }];
    [self.searchBar resignFirstResponder];

}


-(void)creatsearchTableView
{
    
    self.searchTableView = [[UITableView alloc]initWithFrame:CGRectMake(20, 64 + WIDTH / 4, WIDTH - 40, HEIGHT / 2) style:UITableViewStylePlain];
    self.searchTableView.hidden = YES;
    self.searchTableView.backgroundColor = [UIColor clearColor];
    [self.searchTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    self.searchTableView.delegate = self;
    self.searchTableView.dataSource = self;
    self.searchTableView.userInteractionEnabled = YES;
    [self.view addSubview:_searchTableView];

}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
